<?php


function get_component_access_token() {

        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';

        $param ['component_appid'] = 'wx09632c5caa1f84d8';
        $param ['component_appsecret'] = 'b7c4c79ba8a841618205d39c732db2dd';

        $config = ( array ) json_decode ( '{"random":"1","ComponentVerifyTicket":"ticket@@@y2ENapQDybpEgf6sORyqZyYMNHmwoA_LJnTHU9EmcZKwjaZeyz4UVaS2GNawZ4ODnESWXut3NPExOZJ0MlgQlg"}', true );
        $param ['component_verify_ticket'] = $config ['ComponentVerifyTicket'];

        $data = post_data ( $url, $param );
        if (! isset ( $data ['component_access_token'] )) {
            return false;
        }

        $component_access_token = $data ['component_access_token'];

    return $component_access_token;
}
// 获取access_token，自动带缓存功能
function get_access_token() {
    // 微信开放平台一键绑定
    return get_access_token_by_apppid ( 'wx09632c5caa1f84d8', 'b7c4c79ba8a841618205d39c732db2dd' );
}



function wx_curl($url, $post_type = "POST", $data_array, &$errorCode = 0, &$errorMsg = "") {

// 初始化
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    if ($post_type == "GET") {
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
    } else {
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
    }
    $data_json_str = json_encode($data_array);
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_json_str);
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
        'Content-Type: application/json',
        'Content-Length: ' . strlen ( $data_json_str )
    ) );
// 执行并获取接口传的内容
    $ret = curl_exec ( $ch );
    curl_close ( $ch );
    $returnArray = json_decode ( $ret, true );
    return $returnArray;
}
/**
 * POST 请求
 *
 * @param string $url
 * @param array $param
 * @return string content
 */
function http_posts($url, $param) {
    $oCurl = curl_init ();
    if (stripos ( $url, "https://" ) !== FALSE) {
        curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, false );
    }
    if (is_string ( $param )) {
        $strPOST = $param;
    } else {
        $aPOST = array ();
        foreach ( $param as $key => $val ) {
            $aPOST [] = $key . "=" . urlencode ( $val );
        }
        $strPOST = join ( "&", $aPOST );
    }
    curl_setopt ( $oCurl, CURLOPT_URL, $url );
    curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $oCurl, CURLOPT_POST, true );
    curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $strPOST );
    $sContent = curl_exec ( $oCurl );
    $aStatus = curl_getinfo ( $oCurl );
    curl_close ( $oCurl );
    if (intval ( $aStatus ["http_code"] ) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

//获得二维码图片
function downloadImageFromWeiXin($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_NOBODY,0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $package = curl_exec($ch);
    $httpinfo = curl_getinfo($ch);
    curl_close($ch);
    return array_merge(array('body'=>$package),array('header'=>$httpinfo));
}

function get_access_token_by_apppid($appid, $secret) {

    if (empty ( $appid ) || empty ( $secret )) {
        return 0;
    }


    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
    $tempArr = json_decode(httpGet($url));
    if (@array_key_exists ( 'access_token', $tempArr )) {
        $access_token = $tempArr->access_token;
        return $access_token;
    } else {
        return 0;
    }

}

function httpGet($url) {
    $curl = curl_init();
    //$url = 'https://www.baidu.com';
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    //curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18");
    $res = curl_exec($curl);
    //var_dump($res);die();
    curl_close($curl);

    return $res;
}
// 获取当前用户的Token
function get_token($token = NULL) {
    $stoken = session ( 'token' );
    if ($token !== NULL && $token != '-1') {
        session ( 'token', $token );
    } elseif (empty ( $stoken ) && strip_tags ( $_SERVER ['HTTP_HOST'] ) != 'localhost') { // 泛域名支持
        $domain = explode ( '.', strip_tags ( $_SERVER ['HTTP_HOST'] ) );
        $map ['domain'] = $domain [0];
        ! $GLOBALS ['is_wap'] && $GLOBALS ['mid'] && $map ['uid'] = $GLOBALS ['uid'];
        $token = 'b7c4c79ba8a841618205d39c732db2dd';
        $token && session ( 'token', $token );
    }
    $token = session ( 'token' );

    if (empty ( $token ) || $token == '-1') {
        $token = '-1';

    }

    return $token;
}
// 换取公众号的授权信息
function getAuthInfo($auth_code) {
    $res ['status'] = false;

    $component_access_token = get_component_access_token ();
    if ($component_access_token == false) {
        $res ['msg'] = '获取access_token失败！';
        return $res;
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=' . $component_access_token;

    $param ['component_appid'] = 'wxac2a54fc8d293824';
    $param ['authorization_code'] = $auth_code;

    $info = post_data ( $url, $param );
    if (! isset ( $info ['authorization_info'] ['authorizer_appid'] )) {
        $res ['msg'] = '获取authorizer_appid失败！';
        return $res;
    }
    return $info;
}
function get_pre_auth_code($component_access_token = '') {
    empty ( $component_access_token ) && $component_access_token = get_component_access_token ();

    $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=' . $component_access_token;

    $param ['component_appid'] = 'wxac2a54fc8d293824';

    $data = post_data ( $url, $param );
    if (! isset ( $data ['pre_auth_code'] )) {
        return false;
    }

    $pre_auth_code = $data ['pre_auth_code'];

    return $pre_auth_code;
}
// 以POST方式提交数据
function post_data($url, $param, $is_file = false, $return_array = true) {
    if (! $is_file && is_array ( $param )) {
        $param = JSON ( $param );
    }
    if ($is_file) {
        $header [] = "content-type: multipart/form-data; charset=UTF-8";
    } else {
        $header [] = "content-type: application/json; charset=UTF-8";
    }

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
    curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
    curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
    curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $param );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    $res = curl_exec ( $ch );

    //@file_put_contents('license.txt', print_r($param, true), FILE_APPEND);

    $flat = curl_errno ( $ch );



    if ($flat) {
        $data = curl_error ( $ch );
        addWeixinLog ( $flat, 'post_data flat' );
        addWeixinLog ( $data, 'post_data msg' );
    }

    curl_close ( $ch );

    $return_array && $res = json_decode ( $res, true );

    //@file_put_contents('license.txt', print_r($res, true), FILE_APPEND);
    return $res;
}
/**
 * 货到/自提/金额为0
 * @order_id 订单id
 */
function codPayTypeAccess($orderId)
{   $data = ['order_id'=>$orderId,'trade_no'=>'cod'];
    $data['trade_status'] = 'SUCCESS';
    $data['mysign'] = md5($orderId . 'SUCCESS' . 'x0no2mp2vljspdg8ykxlo60w6u2m4n21');
    $result = curl_file_get_contents('http://admin.52ywy.com/notify/confirmorder.php',$data);
    //$result = \App\Libs\Helper::callAdminHaioo('confirmOrder', ['order_id'=>$orderId,'trade_no'=>'cod'], $orderId);
    return $result['status']?true:false;
}

//二维数组去掉重复值
function array_unique_fb($array2D){
    foreach ($array2D as $v){
       // $v=join(',',$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[]= json_encode($v);
    }
    $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v){
        $v = json_decode($v,true);
        $temp[$k]=$v; //再将拆开的数组重新组装
    }
    return $temp;
}

/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc') {
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

/**
 * HTTP请求方法
 *
 * @author gxd
 * @param unknown $durl
 * @param unknown $data
 * @return mixed
 */
function curl_file_get_contents($durl, $data = array(), $header = array())
{
    $ch = curl_init();
    if (! empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }else{
        $header [] = "content-type: application/json; charset=UTF-8";
    }

    curl_setopt($ch, CURLOPT_URL, $durl);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (! empty($data)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $r = curl_exec($ch);
    if ($r) {
        curl_close($ch);
        return $r;
    } else {
        $error = curl_errno($ch);
        curl_close($ch);
        return 'error:' . $error;
    }
}

/**
 * 物流查询接口
 */
function logistics($num,$com){
    //参数设置
    $post_data = array();
    $post_data["customer"] = '6B87E482441CD2AE1E3E84F48D94E7F8';
    $key= 'cqKCQioo1556' ;
    $post_data["param"] = "{'com':'$com','num':'$num'}";

    $url='http://poll.kuaidi100.com/poll/query.do';
    $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
    $post_data["sign"] = strtoupper($post_data["sign"]);
    $o="";
    foreach ($post_data as $k=>$v)
    {
        $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
    }
    $post_data=substr($o,0,-1);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    // curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);


    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);

    $result = curl_exec($ch);
    $data = str_replace("\&quot;",'"',$result );
    $data = json_decode($data,true);
    return $data;
}

/**
 * 获取支付密码的加密字符串
 * @param unknown $password
 */
function getEncodePayPasswrod($password)
{
    $pwdEncode = substr(hash('sha512', 'pay_pwd_'.$password), 0, 32);
    return $pwdEncode;
}

/**
 * 计算2个日期之间的天数
 * @param $date1  开始时间
 * @param $date2  结束时间
 */
function getdays($date1,$date2){

    $day = (strtotime($date2)-$date1)/24/3600;
    return floor($day);
}
/**
 * 将字符串转换为数组
 *
 * @param    string $data 字符串
 * @return    array    返回数组格式，如果，data为空，则返回空数组
 */
function string2array($data)
{
    $data = trim($data);
    if ($data == '') return array();
    if (strpos($data, 'array') === 0) {
        @eval("\$array = $data;");
    } else {
        if (strpos($data, '{\\') === 0) $data = stripslashes($data);
        $array = json_decode($data, true);
        if (strtolower(CHARSET) == 'gbk') {
            $array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
        }
    }
    return $array;
}

/**
 * 将数组转换为字符串
 *
 * @param    array $data 数组
 * @param    bool $isformdata 如果为0，则不使用new_stripslashes处理，可选参数，默认为1
 * @return    string    返回字符串，如果，data为空，则返回空
 */
function array2string($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    if ($isformdata) $data = stripslashes($data);
    if (strtolower(CHARSET) == 'gbk') {
        $data = mult_iconv("GBK", "UTF-8", $data);
    }
    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return addslashes(json_encode($data));
    } else {
        return addslashes(json_encode($data, JSON_FORCE_OBJECT));
    }
}

/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...')
{
    //$string = iconv("UTF-8","GB2312",$string);
    $strlen = strlen($string);
    if ($strlen <= $length) {
        return $string;
    }

    $string = str_replace(array(' ', '&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵', ' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
    $strcut = '';
    //  if (strtolower(CHARSET) == 'utf-8') {
    $length = intval($length - strlen($dot) - $length / 3);
    $n = $tn = $noc = 0;
    while ($n < strlen($string)) {
        $t = ord($string[$n]);
        if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1;
            $n++;
            $noc++;
        } elseif (194 <= $t && $t <= 223) {
            $tn = 2;
            $n += 2;
            $noc += 2;
        } elseif (224 <= $t && $t <= 239) {
            $tn = 3;
            $n += 3;
            $noc += 2;
        } elseif (240 <= $t && $t <= 247) {
            $tn = 4;
            $n += 4;
            $noc += 2;
        } elseif (248 <= $t && $t <= 251) {
            $tn = 5;
            $n += 5;
            $noc += 2;
        } elseif ($t == 252 || $t == 253) {
            $tn = 6;
            $n += 6;
            $noc += 2;
        } else {
            $n++;
        }
        if ($noc >= $length) {
            break;
        }
    }
    if ($noc > $length) {
        $n -= $tn;
    }
    $strcut = substr($string, 0, $n);
    $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
    //  } else {
    //      $dotlen      = strlen($dot);
    //      $maxi        = $length-$dotlen-1;
    //      $current_str = '';
    //      $search_arr  = array('&', ' ', '"', "'", '“', '”', '—', '<', '>', '·', '…', '∵');
    //      $replace_arr = array('&amp;', '&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;', ' ');

    //      $search_flip = array_flip($search_arr);
    //      for ($i = 0; $i < $maxi; $i++) {
    //          $current_str = ord($string[$i]) > 127?$string[$i].$string[++$i]:$string[$i];
    //          if (in_array($current_str, $search_arr)) {
    //              $key         = $search_flip[$current_str];
    //              $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
    //          }
    //          $strcut .= $current_str;
    //      }
    //  }

    //$strcut = iconv("GB2312","UTF-8",$strcut);
    return $strcut . $dot;
}

/**
 * 对用户的密码进行加密
 * @param $password
 * @param $encrypt //传入加密串，在修改密码时做认证
 * @return array/password
 */
function password($password, $encrypt = '')
{
    $pwd = array();
    $pwd['encrypt'] = $encrypt ? $encrypt : create_randomstr();
    $pwd['password'] = md5(md5(trim($password)) . $pwd['encrypt']);
    return $encrypt ? $pwd['password'] : $pwd;
}

/**
 * 生成随机字符串
 * @param string $lenth 长度
 * @return string 字符串
 */
function create_randomstr($lenth = 6)
{
    return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}

/**
 * 产生随机字符串
 *
 * @param    int $length 输出长度
 * @param    string $chars 可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

/**
 * Introduction: 生成无限极分类数组
 * Date: 15/11/16
 * Time: 10:23
 * Last date: 15/11/16 10:23
 * Last user: arpeng
 * @param  array $items 无限极分类一维数组
 * @param  $name  string 子级下标
 */
function generateTree($items, $name = 'child')
{
//    foreach($rule as $v)
//        $rules[$v['id']] = $v;
    $tree = array();
    foreach ($items as $item) {
        if (isset($items[$item['pid']])) {
            $items[$item['pid']][$name][] = &$items[$item['id']];
        } else {
            $tree[] = &$items[$item['id']];
        }
    }
    return $tree;
}

/**
 * Introduction: 给图片连接添加参数,方便程序裁剪图片
 * Date: 15/12/13
 * Time: 20:31
 * Last date: 15/12/13 20:31
 * Last user: arpeng
 * @param  string $url 需要添加参数的URL
 * @param  int || string  $width  宽度
 * @param  int || string  $height  高度
 */
function cutUrl($url, $width, $height)
{
    if (!$url) return '';
    $info = pathinfo($url);
    return $info['dirname'] . '/' . $info['filename'] . '_' . $width . '_' . $height . '.' . $info['extension'];
}

/**
 * Introduction: 冒泡排序   用于blog  basic排序使用
 * Date: 15/12/14
 * Time: 18:28
 * Last date: 15/12/14 18:28
 * Last user: arpeng
 */
function bubbleSort($array)
{
    $count = count($array);
    for ($i = 0; $i < $count; $i++) {
        for ($j = 0; $j < $count - $i - 1; $j++) {
            if ($array[$j]['sort'] > $array[$j + 1]['sort']) {
                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
            }
        }
    }
    return $array;
}

/**
 * Introduction: 获取注册时和登录时的用户名类型
 * Date: 16/01/30
 * Time: 12:28
 * Last date: 16/01/30 12:28
 * @param $sign String 登录时或者注册是输入的用户名
 */
function getSignType($sign)
{
    if (!$sign) return false;
    $return = [];
    $regxSign = [
        'mobile' => "/^1[3|4|5|6|7|8]\d{9}$/",
        'email' => "/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/",
        'username' => "/^[a-zA-Z0-9-_]+$/",
    ];
    foreach ($regxSign as $k => $v) {
        if (preg_match($v, $sign)) {
            $return[$k] = strtolower($sign);
            $return['type'] = $k;
            break;
        }
    }
    return $return;
}
/**
 * Introduction: 二维数组去重复
 * @param $data array 需要去重复的二维数组
 */
function unique($data = array()){

    $tmp = array();

    foreach($data as $key => $value){

        foreach($value as $key1 => $value1){

            $value[$key1] = $key1 . '_|_' . $value1;//_|_分隔符复杂点以免冲突

        }

        $tmp[$key] = implode(',|,', $value);//,|,分隔符复杂点以免冲突

    }
    $tmp = array_unique($tmp);

    $newArr = array();

    foreach($tmp as $k => $tmp_v){

        $tmp_v2 = explode(',|,', $tmp_v);

        foreach($tmp_v2 as $k2 => $v2){

            $v2 = explode('_|_', $v2);

            $tmp_v3[$v2[0]] = $v2[1];

        }

        $newArr[$k] = $tmp_v3;

    }

    return $newArr;

}

/**
 * 二维数组排序
 * @param array $list
 * @param string $field
 * @param string $sortby
 * @return array|boolean
 */
function listSortBy($list, $field, $sortby = 'asc')
{
    if (is_array($list)) {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = $data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = $list[$key];
        return $resultSet;
    }
    return false;
}
/**
 * 获取支付总价
 *
 * @param unknown_type $orderInfo
 *            订单信息
 */
function getPayPrice($orderInfo)
{
    $price = 0;
    $cost = isset($orderInfo['cost'])?$orderInfo['cost']:0;
    $totalPrice = isset($orderInfo['total_price'])?$orderInfo['total_price']:0;
    $cpnsPrice = isset($orderInfo['cpns_price'])?$orderInfo['cpns_price']:0;
    $freight = isset($orderInfo['freight'])?$orderInfo['freight']:0;
    $freightPrice = isset($orderInfo['freight_price'])?$orderInfo['freight_price']:0;
    $cashPrice = isset($orderInfo['cash_price'])?$orderInfo['cash_price']:0;
    $taxPrice = isset($orderInfo['tax_price'])?$orderInfo['tax_price']:0;
    $mstaxation = isset($orderInfo['total_ms_taxation'])?$orderInfo['total_ms_taxation']:0;
    $ms_Freight_risk = isset($orderInfo['ms_Freight_risk'])?$orderInfo['ms_Freight_risk']:0;
    if(!empty($orderInfo)){
        $price = ($cost ? $cost : $totalPrice) - $cpnsPrice + ($freight ? $freight : $freightPrice) + $mstaxation + $ms_Freight_risk + $taxPrice - $cashPrice;
    }

    return $price;
}


/**
 * 字符串加密解密
 * $operation  DECODE 解密   ENCODE加密
 * $string  要加密的字符串
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $key = 'webapi.52ywy.com';
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length):
        substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
    //解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
        sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}
/**
 * 对提供的数据进行urlsafe的base64编码。
 *
 * @param string $data 待编码的数据，一般为字符串
 *
 * @return string 编码后的字符串
 * @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64
 */
function base64_urlSafeEncode($data)
{
    $find = array('+', '/');
    $replace = array('-', '_');
    return str_replace($find, $replace, base64_encode($data));
}

/**
 * 对提供的urlsafe的base64编码的数据进行解码
 *
 * @param string $str 待解码的数据，一般为字符串
 *
 * @return string 解码后的字符串
 */
function base64_urlSafeDecode($str)
{
    $find = array('-', '_');
    $replace = array('+', '/');
    return base64_decode(str_replace($find, $replace, $str));
}

/**
 * 获取金额之间的随机数
 * @param int $min
 * @param int $max
 * @return int
 */

function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
/**
 * array 辅助方法，无值时不set
 *
 * @param $array 待操作array
 * @param $key key
 * @param $value value 为null时 不设置
 *
 * @return array 原来的array，便于连续操作
 */
function setWithoutEmpty(&$array, $key, $value)
{
    if (!empty($value)) {
        $array[$key] = $value;
    }
    return $array;
}

/**
 * 计算七牛API中的数据格式
 *
 * @param $bucket 待操作的空间名
 * @param $key 待操作的文件名
 *
 * @return string  符合七牛API规格的数据格式
 * @link http://developer.qiniu.com/docs/v6/api/reference/data-formats.html
 */
function entry($bucket, $key)
{
    $en = $bucket;
    if (!empty($key)) {
        $en = $bucket . ':' . $key;
    }
    return base64_urlSafeEncode($en);
}
/**
 * 计算输入流的crc32检验码
 *
 * @param $data 待计算校验码的字符串
 *
 * @return string 输入字符串的crc32校验码
 */
function crc32_data($data)
{
    $hash = hash('crc32b', $data);
    $array = unpack('N', pack('H*', $hash));
    return sprintf('%u', $array[1]);
}